package xiaolong.zhou.spring_demo.Service.achieve;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import xiaolong.zhou.spring_demo.Mapper.UserMapper;
import xiaolong.zhou.spring_demo.Pojo.Register;
import xiaolong.zhou.spring_demo.Pojo.User;
import xiaolong.zhou.spring_demo.Service.UserRegister;
import xiaolong.zhou.spring_demo.Utils.Result;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class UserRegisterAchieve implements UserRegister {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户注册具体实现
     * @param register
     * @return
     */
    @Override
    public Result register(Register register){
        //验证参数
        if(register.getPhone()==null||register.getEmail()==null||register.getPassword()==null){
            return Result.error("参数有误");
        }
        if(!register.getPassword().equals(register.getRepassword())){
            return  Result.error("密码不一致");
        }
        //检测验证码
        if(register.getSessionId() == null){
            return Result.error("图形验证码校验失效");
        }

        if(redisTemplate.opsForValue().get(register.getSessionId()) == null){
            return Result.error("图形验证码过期");
        }
        if(!Objects.equals(redisTemplate.opsForValue().get(register.getSessionId()), register.getCaptcha().toLowerCase())){
            return Result.error("图形验证码错误");
        }
        if(redisTemplate.opsForValue().get(register.getEmail()) == null){
            return Result.error("邮箱验证码过期");
        }
        if(!Objects.equals(redisTemplate.opsForValue().get(register.getEmail()), register.getEmailCaptcha().toLowerCase())){
            return Result.error("邮箱验证码错误");
        }
        //删除缓存验证码
        redisTemplate.delete(register.getEmail());
        redisTemplate.delete(register.getSessionId());
        //添加数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",register.getPhone());
        Long userCount = userMapper.selectCount(queryWrapper);
        User user = new User();
        if(userCount>0){
            return Result.error("该手机号已注册");
        }
        user.setUser(register.getUsername());
        user.setPhone(register.getPhone());
        user.setPrice((float) 0.00);
        user.setEmail(register.getEmail());
        user.setPassword(DigestUtils.md5DigestAsHex(register.getPassword().getBytes()));
        user.setAvatar("");
        user.setDeleteTime("");
        user.setCreateTime(new Date().toString());
        userMapper.insert(user);
        return Result.success();
    }
}
